package com.jiuyin.dianjing.ui.activity.match;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.api.base.DefaultApiResult;
import com.jiuyin.dianjing.api.enums.ApiEnum;
import com.jiuyin.dianjing.api.interfaces.ApiResultCallback;
import com.jiuyin.dianjing.api.server.ServerApi;
import com.jiuyin.dianjing.app.HelperApplication;
import com.jiuyin.dianjing.event.RefreshEvent;
import com.jiuyin.dianjing.model.FileModel;
import com.jiuyin.dianjing.model.MatchDataModel;
import com.jiuyin.dianjing.permission.XPermission;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.ui.fragment.match.FragmentMatchGameData;
import com.jiuyin.dianjing.util.FileUtils;
import com.jiuyin.dianjing.util.IMEUtil;
import com.jiuyin.dianjing.util.LogUtil;
import com.jiuyin.dianjing.util.ToastUtil;
import com.lzy.okgo.cache.CacheMode;
import com.rain.library.bean.Photo;
import com.rain.library.controller.PhotoPickConfig;
import com.rain.library.glide.GlideImageLoader;
import com.rain.library.impl.PhotoSelectCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.listeners.OnMoreItemPickListener;
import cn.addapp.pickers.picker.LinkagePicker;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COMPETITION_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_COMPET_SINGLE_DATA_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_GRADE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_LINEUP;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_POST;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_RACE;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_RECORD_KEEP_ID;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_SCREEN_SHOT;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TOKEN;
import static com.jiuyin.dianjing.api.enums.ApiEnum.APP_UPDATE_COMPETE_DATA_SINGLE_API;
import static com.jiuyin.dianjing.constant.AppConstant.FOLDER_NAME;
import static com.jiuyin.dianjing.constant.AppConstant.MAX_PHOTO_SIZE;

/**
 * 比赛数据详情
 */
public class MatchDataActivity extends BaseActivity {
    @BindView(R.id.pic)
    BGASortableNinePhotoLayout mPhotosSnpl;
    @BindView(R.id.tv_player1_score)
    TextView mPlayer1Score;
    @BindView(R.id.tv_player1_name)
    TextView mPlayer1Name;
    @BindView(R.id.tv_player2_score)
    TextView mPlayer2Score;
    @BindView(R.id.tv_player2_name)
    TextView mPlayer2Name;
    @BindView(R.id.img_player1)
    ImageView mPlayer1Logo;
    @BindView(R.id.img_player2)
    ImageView mPlayer2Logo;
    @BindView(R.id.tv_game_submit)
    TextView btPublish;

    private String mOriginLeftScore;
    private String mOriginRightScore;
    private String mCompetsingledataId;
    private String mCompetitionId;
    private String mRace;
    private String mPlayer1RecordKeepId;
    private String mPlayer2RecordKeepId;
    private String mPlayer1LineUP;
    private String mPlayer2LineUP;
    /**
     * 是否提交左面的比分
     */
    boolean isSubmitLeft;
    /**
     * 是否提交右面的比分
     */
    boolean isSubmitRight;
    private static final int RC_CHOOSE_PHOTO = 1;
    private static final int RC_PHOTO_PREVIEW = 2;

    private StringBuilder photoBuilder;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_match_data;
    }

    @Override
    protected void initData() {
        mPhotosSnpl.setDelegate(new BGASortableNinePhotoLayout.Delegate() {
            @Override
            public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
                choicePhotoWrapper();
            }

            @Override
            public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
                mPhotosSnpl.removeItem(position);
            }

            @Override
            public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
                Intent photoPickerPreviewIntent = new BGAPhotoPickerPreviewActivity.IntentBuilder(MatchDataActivity.this)
                        .previewPhotos(models) // 当前预览的图片路径集合
                        .selectedPhotos(models) // 当前已选中的图片路径集合
                        .maxChooseCount(mPhotosSnpl.getMaxItemCount()) // 图片选择张数的最大值
                        .currentPosition(position) // 当前预览图片的索引
                        .isFromTakePhoto(false) // 是否是拍完照后跳转过来
                        .build();
                startActivityForResult(photoPickerPreviewIntent, RC_PHOTO_PREVIEW);
            }

            @Override
            public void onNinePhotoItemExchanged(BGASortableNinePhotoLayout sortableNinePhotoLayout, int fromPosition, int toPosition, ArrayList<String> models) {
                Toast.makeText(MatchDataActivity.this, "排序发生变化", Toast.LENGTH_SHORT).show();
            }

            private void choicePhotoWrapper() {
                new PhotoPickConfig
                        .Builder(MatchDataActivity.this)
                        .imageLoader(new GlideImageLoader())
                        .pickMode(PhotoPickConfig.MODE_PICK_MORE)
                        .maxPickSize(MAX_PHOTO_SIZE - mPhotosSnpl.getItemCount())
                        .showCamera(true)
                        .setCallback(new PhotoSelectCallback() {
                            @Override
                            public void moreSelect(ArrayList<Photo> photos) {
                                selectPhoto(photos);
                            }

                            @Override
                            public void singleSelect(ArrayList<Photo> photos) {
                                selectPhoto(photos);
                            }

                            private void selectPhoto(ArrayList<Photo> photos) {
                                int size = photos.size();
                                ArrayList<String> list = new ArrayList<>(size);
                                if (PhotoPickConfig.DEFAULT_START_COMPRESSION) {
                                    for (int i = 0; i < size; i++) {
                                        list.add(photos.get(i).getCompressionImagePath());
                                    }
                                } else {
                                    for (int i = 0; i < size; i++) {
                                        if (!TextUtils.isEmpty(photos.get(i).getCameraImagePath())){
                                            list.add(photos.get(i).getCameraImagePath());
                                        }else {
                                            list.add(photos.get(i).getOriginalImagePath());
                                        }
                                    }
                                }
                                mPhotosSnpl.addMoreData(list);
                            }
                        }).build();
            }
        });
        Bundle bundle = getIntent().getExtras();
        MatchDataModel matchDataModel = (MatchDataModel) bundle.getSerializable(KEY_POST);
        mOriginLeftScore = matchDataModel.player1Score;
        mOriginRightScore = matchDataModel.player2Score;

        mPlayer1Score.setText(matchDataModel.player1Score);
        mPlayer2Score.setText(matchDataModel.player2Score);
        mPlayer1Name.setText(matchDataModel.player1Name);
        mPlayer2Name.setText(matchDataModel.player2Name);
        mCompetitionId = matchDataModel.competition_id;
        mRace = matchDataModel.race;
        mPlayer1RecordKeepId = matchDataModel.player1RecordKeepId;
        mPlayer2RecordKeepId = matchDataModel.player2RecordKeepId;
        mPlayer1LineUP = matchDataModel.player1Lineup;
        mPlayer2LineUP = matchDataModel.player2Lineup;
        mCompetsingledataId = matchDataModel.competsingledata_id;
        Glide.with(this).load(matchDataModel.player1Logo).into(mPlayer1Logo);
        Glide.with(this).load(matchDataModel.player2Logo).into(mPlayer2Logo);
    }


    @Override
    protected void initView() {
        setTitle(R.string.match_detail_data);
        doPermission();
    }


    private void submit() {
        uploadFiles();
    }


    @OnClick({R.id.tv_game_submit, R.id.cl_match})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_game_submit:
                submit();
                break;
            case R.id.cl_match:
                onLinkagePicker();
                break;
        }
    }

    /**
     * 动态请求照相和存储权限
     */
    private void doPermission() {
        XPermission.requestPermissions(this, 101, new String[]{Manifest.permission
                .WRITE_EXTERNAL_STORAGE}, new XPermission.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {

            }

            @Override
            public void onPermissionDenied() {
                XPermission.showTipsDialog(MatchDataActivity.this);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RC_CHOOSE_PHOTO:
                    mPhotosSnpl.addMoreData(BGAPhotoPickerActivity.getSelectedPhotos(data));
                    break;
                case RC_PHOTO_PREVIEW:
                    mPhotosSnpl.setData(BGAPhotoPickerPreviewActivity.getSelectedPhotos(data));
                    break;
            }
        }
    }

    /**
     * 选择比分
     */
    private void onLinkagePicker() {
        LinkagePicker.DataProvider provider = new LinkagePicker.DataProvider() {
            @Override
            public boolean isOnlyTwo() {
                return true;
            }

            @Override
            public List<String> provideFirstData() {
                return getList();
            }

            @Override
            public List<String> provideSecondData(int firstIndex) {
                return getList();
            }

            @Override
            public List<String> provideThirdData(int firstIndex, int secondIndex) {
                return null;
            }
        };
        LinkagePicker picker = new LinkagePicker(this, provider);
        picker.setCanLoop(true);
        picker.setLabel(getString(R.string.match_data_vs), "");
        picker.setSelectedIndex(Integer.parseInt(mPlayer1Score.getText().toString()), Integer.parseInt(mPlayer2Score.getText().toString()));
        picker.setOnMoreItemPickListener((OnMoreItemPickListener<String>) (first, second, third) -> {
                mPlayer1Score.setText(first);
                mPlayer2Score.setText(second);
        });
        picker.show();
    }

    /**
     * 提交比分
     */
    private void submitScore() {
        String player1Score = mPlayer1Score.getText().toString();
        String player2Score = mPlayer2Score.getText().toString();
        isSubmitLeft = player1Score.equals(mOriginLeftScore) ? false : true;
        isSubmitRight = player2Score.equals(mOriginRightScore) ? false : true;
        if (isSubmitLeft) {
            submitLeft();
        } else {
            if (isSubmitRight) {
                submitRight();
            }
        }
    }

    /**
     * 比分数据
     *
     * @return
     */
    private List<String> getList() {
        List<String> firstList = new ArrayList<>();
        for (int i = 0; i <= 5; i++) {
            firstList.add(String.valueOf(i));
        }
        return firstList;
    }

    /**
     * 提交左面的比分
     */
    private void submitLeft() {
        HashMap<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, HelperApplication.getToken());
        params.put(KEY_RECORD_KEEP_ID, mPlayer1RecordKeepId);
        params.put(KEY_GRADE, mPlayer1Score.getText().toString());
        params.put(KEY_COMPET_SINGLE_DATA_ID, mCompetsingledataId);
        params.put(KEY_LINEUP, mPlayer1LineUP);
        params.put(KEY_COMPETITION_ID, mCompetitionId);
        params.put(KEY_RACE, mRace);
        JSONObject jsonObject = new JSONObject(params);
        ServerApi.post(APP_UPDATE_COMPETE_DATA_SINGLE_API.getUrl(), jsonObject, CacheMode.NO_CACHE, null, d -> addDisposable(d),
                new ApiResultCallback() {
                    @Override
                    public void onSuccess(JsonObject jsonObject) {
                        LogUtil.log("submitLeft onSuccess jsonObject = " + jsonObject.toString());
                        if (isSubmitRight) {
                            submitRight();
                        } else {
                            IMEUtil.hideInputMethod(MatchDataActivity.this);
                            EventBus.getDefault().post(new RefreshEvent(FragmentMatchGameData.class.getSimpleName()));
                            finish();
                        }
                    }

                    @Override
                    public void onFail(String msg) {
                        LogUtil.log("submitLeft onFail msg = " + msg);
                        btPublish.setEnabled(true);
                    }

                    @Override
                    public void onError(String msg) {
                        LogUtil.log("submitLeft onError msg = " + msg);
                        btPublish.setEnabled(true);
                    }
                });
    }

    /**
     * 提交右面的比分
     */
    private void submitRight() {
        HashMap<String, Object> paramsRight = new HashMap<>();
        paramsRight.put(KEY_TOKEN, HelperApplication.getToken());
        paramsRight.put(KEY_RECORD_KEEP_ID, mPlayer2RecordKeepId);
        paramsRight.put(KEY_GRADE, mPlayer2Score.getText().toString());
        paramsRight.put(KEY_COMPET_SINGLE_DATA_ID, mCompetsingledataId);
        paramsRight.put(KEY_LINEUP, mPlayer2LineUP);
        paramsRight.put(KEY_COMPETITION_ID, mCompetitionId);
        paramsRight.put(KEY_RACE, mRace);
        JSONObject jsonObjectRight = new JSONObject(paramsRight);
        ServerApi.post(APP_UPDATE_COMPETE_DATA_SINGLE_API.getUrl(), jsonObjectRight, CacheMode.NO_CACHE, null, d -> addDisposable(d),
                new ApiResultCallback() {
                    @Override
                    public void onSuccess(JsonObject jsonObject) {
                        LogUtil.log("submitRight onSuccess jsonObjectRight = " + jsonObject.toString());
                        IMEUtil.hideInputMethod(MatchDataActivity.this);
                        EventBus.getDefault().post(new RefreshEvent(FragmentMatchGameData.class.getSimpleName()));
                        finish();
                    }

                    @Override
                    public void onFail(String msg) {
                        btPublish.setEnabled(true);
                        LogUtil.log("submitRight onFail msg = " + msg);
                    }

                    @Override
                    public void onError(String msg) {
                        btPublish.setEnabled(true);
                        LogUtil.log("submitRight onError msg = " + msg);
                    }
                });

    }

    /**
     * 上传文件
     */
    private void uploadFiles() {
        ArrayList<String> list = mPhotosSnpl.getData();
        if (null == list || 0 == list.size()) {
            ToastUtil.showShort(R.string.photo_not_select);
            return;
        }
        btPublish.setEnabled(false);
        photoBuilder = new StringBuilder();
        final List<FileModel> files = new ArrayList<>();
        for (String filePath : mPhotosSnpl.getData()) {
            String fileName = FileUtils.generateFileName(filePath);
            fileName = FOLDER_NAME + fileName;
            photoBuilder.append("http://jiuyinesports.com/").append(fileName).append(",");
            FileModel fileModel = new FileModel(fileName, filePath);
            files.add(fileModel);
        }
        if (photoBuilder.length() > 0) {
            photoBuilder.deleteCharAt(photoBuilder.length() - 1);
        }
        showLoading();

        //上传图片到阿里云OSS
        OSSCompletedCallback<PutObjectRequest, PutObjectResult> userCallback = new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            private int time = 0;

            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                int size = files.size();
                LogUtil.log("MatchDataActivity UploadSuccess");
                String fileName = request.getObjectKey();
                for (FileModel file : files) {
                    if (file.fileName.equals(fileName)) {
                        time++;
                        file.success = true;
                        break;
                    }
                }
                if (time == size) {
                    dismissLoading();
                    publish();
                }
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                if (clientException != null) {
                    ToastUtil.showShort("客户端异常:图片上传失败");
                    LogUtil.log(clientException.getMessage());
                }
                if (serviceException != null) {
                    ToastUtil.showShort("服务端异常:图片上传失败");
                    LogUtil.log(serviceException.getMessage());
                }
                btPublish.setEnabled(true);
                dismissLoading();
            }
        };
        HelperApplication.ossService.asyncPutImages(files, userCallback, null);
    }

    private void publish() {
        HashMap<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, HelperApplication.getToken());
        params.put(KEY_SCREEN_SHOT, photoBuilder.toString());//图片地址（用逗号拼接）
        params.put(KEY_COMPET_SINGLE_DATA_ID, mCompetsingledataId);
        JSONObject jsonObject = new JSONObject(params);
        ApiResultCallback requestCallback = new DefaultApiResult() {
            @Override
            public void onSuccess(JsonObject data) {
                submitScore();
            }

            @Override
            public void onFail(String msg) {
                super.onFail(msg);
                btPublish.setEnabled(true);
            }

            @Override
            public void onError(String msg) {
                super.onError(msg);
                btPublish.setEnabled(true);
            }
        };
        ServerApi.post(ApiEnum.APP_UPDATE_COMPET_SCREEN_SHOT.getUrl(), jsonObject, null, progress, null, requestCallback);
    }
}
